<?php

class XmlToCsv {

    function __construct() {
        
    }

    public function convert($doc) {
        $nodelist = $doc->getElementsByTagName('*');
        for ($i = 0; $i < $nodelist->length; $i++) {
            if ($nodelist->item($i)->childNodes->length <= 1) {
                $tags[$nodelist->item($i)->nodeName] = $nodelist->item($i)->nodeName;
            }
        }
        $atributos = "";
        foreach ($tags as $value) {
            $atributos = $atributos . $value . ",";
        }
        $csv = fopen('file.csv', 'w');
        fwrite($csv, $atributos);
        $validador = true;
        $interacao = 0;
        $q = 0;
        while ($validador) {
            $linha = "";
            foreach ($tags as $value) {
                $q = $doc->getElementsByTagName($value)->length;
                $linha = $linha . $doc->getElementsByTagName($value)->item($interacao)->nodeValue . ",";
            }
            fwrite($csv, $linha);
            $interacao++;
            if ($interacao >= $q) {
                $validador = false;
            }
        }
        fclose($csv);
        header("Location: file.csv");
    }

}